<?php
namespace app\single\controller;
use think\Db;
/**
 * #用户名片相关 {关于用户名片相关}
 */
class Testweixin extends Common{
    /**
     * 获取用户今日可发布名片量，总可发量，每张名片金额
     * @return [type] [description]
     */
    function setting($isJson=true){
        $uid=$this->user['id'];
        $nums=0;
        $user=model('member')->read(['id'=>$uid],'vip_level,coin,coin_expire');
        $isVip=model('member')->isVip($uid);
        if($isVip){
            $nums=$user['vip_level']*2;
            $nowTime=strtotime(date('Y-m-d'));
            $_nums=model('Testweixin')->where([
                'uid'=>$uid,
                's_time'=>['s_time','>=',$nowTime]
            ])->count();
            $nums-=$_nums;
            
        }
        $count=model($this->table)->where(['uid'=>$uid])->count();
        $res=[
            'count'=>$count, //已发产品总数
            'nums'=>$nums, //该用户今日可发产品数量
            'nums2'=>$user['vip_level']*2, //每日最多可发产品数量
            'money'=>config('setting.card_coin'),
            'coin'=>$user['coin_expire']>time()?99999:$user['coin'],
            'coin_expire'=>$user['coin_expire'],
        ];
        if($isJson){
            return json('',0,$res);
        }
        return $res;
    }
    /**
     * 点击量
     * @param  integer $id [description]
     * @return [type]      [description]
     */
    function clicks($id=0){
        model($this->table)->where(['id'=>$id])->setInc('clicks');
        return json('');
    }
    /**
     * 随机返回10条微信数据（当前数据为虚拟数据）
     * @param  integer $city 城市ID
     * @param  integer $attr 属性ID
     * @param  integer $sex  0：女 1：男 2：不限
     * @param  integer $sort 0:正序 1：倒序 2:最热排序（点击量倒序）
     * @param  integer $type 1: 好友 2：群
     * @return [type]        [description]
     */
    function index($city=0,$attr=0,$sex=2,$sort=1,$type=1){
        $len=10;
        $index=0;
        $uid=$this->user['id'];
        $map=[
            'uid'=>['uid','<>',$uid],
            'type'=>$type,
            'isUp'=>0,
        ];
        if($type==2){
            //$map['qrcode_time']=['qrcode_time','>',time()]; //群二维码未过期
        }
        if($sex==0||$sex==1){
            $map['sex']=$sex;
        }
        if($city>0){
            $map['city_id']=$city;
        }
        if($attr>0){
            $map['attr_str']=['attr_str','like',"%,".$attr."%"];
        }
        $order='e_time';
        if($sort>1){
            $order='clicks desc';
        }elseif($sort>0){
            $order='e_time desc';
        }
        $count=model($this->table)->where($map)->count();
        if($count-$len>0){
            $index=rand(0,$count-$len);
        }
        $field='id,wxId,head_img,tel,nickName,city_id,sex,qrcode,type,remark,clicks,s_time,isUp';
        $list=model($this->table)->where($map)->limit($index,$len)->with(['city','attr'])->order($order)->field($field)->select()->toArray();
        $prefix=request()->domain();
        $suffix='.jpg';
        foreach ($list as $k => $v) {
            if(false!==strpos($v['head_img'], '/')){
                $list[$k]['head_img']=images($v['head_img']);
            }else{
                $list[$k]['head_img']=$prefix.'/testheadimg/'.$v['head_img'].$suffix;
            }
            if(false!==strpos($v['qrcode'], '/')){
                $list[$k]['qrcode']=images($v['qrcode']);
            }else{
                $list[$k]['qrcode']=$prefix.'/testqrcode/'.$v['qrcode'].$suffix;
            }
            $list[$k]['attr']=empty($v['attr'])?'':$v['attr'][0]['name'];
        }
        return json('',0,$list); 
    }
    /**
     * 获取我的个人、群组名片列表
     * @param  integer $type 1：个人名片，2：群名片
     * @return [type]        [description]
     */
    function mine($type=1){
        $uid=$this->user['id'];
        $map=[
            'uid'=>$uid,
            'type'=>$type
        ];
        $options=[
            'with'=>['city','attr'],
            'field'=>'id,wxId,head_img,tel,nickName,city_id,sex,qrcode,type,remark,clicks,s_time,isUp',
        ];
        $list=model($this->table)->readAll($map,0,$options)->toArray();
        $prefix=request()->domain();
        $suffix='.jpg';
        foreach ($list as $k => $v) {
            if(false!==strpos($v['head_img'], '/')){
                $list[$k]['head_img']=images($v['head_img']);
            }else{
                $list[$k]['head_img']=$prefix.'/testheadimg/'.$v['head_img'].$suffix;
            }
            if(false!==strpos($v['qrcode'], '/')){
                $list[$k]['qrcode']=images($v['qrcode']);
            }else{
                $list[$k]['qrcode']=$prefix.'/testqrcode/'.$v['qrcode'].$suffix;
            }
            $list[$k]['attr']=empty($v['attr'])?'':$v['attr'][0]['name'];
        }
        return json('',0,$list);
    }
    
    /**
     * 发布名片
     * @param  string  $wxId    微信ID
     * @param  integer $type    1:个人名片、2：群名片
     * @param  string  $remark  介绍说明
     * @param  string  $tel     联系电话
     * @param  integer  $city_id 城市ID
     * @param  string|array  $attr    名片标签
     * @return [type]           [description]
     */
    function release($wxId=null,$type=2,$remark='',$tel=null,$city_id=null,$attr=null,$nickName=null,$sex=0,$qrcode_text=null){
        $uid=$this->user['id'];
        $user=model('member')->read(['id'=>$uid],'id,head_img,name,wxId,tel,qrcode,city_id,is_perfect,vip_level,vip_expire');
        if(!$user['is_perfect']){
            //return json('请先完善您的个人信息',1);
        }
        if(!$user['vip_level']){
            return json('请您先开通VIP',1);
        }
        if($user['vip_expire']<time()){
            model('member')->isVip($uid);
            return json('您的VIP已过期',1);
        }
        $setting=$this->setting(false);
        if(!$setting['nums']){
            return json('今日额度已用完，请您明日再发布',1);
        }
        if($setting['coin']<$setting['money']){
            return json('您的'.lang('coin').'数量不足，请先充值',1);
        }
        if(is_string($attr)){
            $attr=json_decode($attr,true);
        }
        $data=[
            'wxId'=>$wxId,
            'type'=>$type,
            'remark'=>$remark,
            'tel'=>$tel,
            'sex'=>$sex,
            'city_id'=>$city_id,
            'nickName'=>$nickName,
            'qrcode_text'=>md5($qrcode_text),
        ];
        $validate=$this->validate($data,[
            //'nickName|昵称'=>'require',
            'remark|名片说明'=>'require',
        ]);
        if(true!==$validate){
            return json($validate,1);
        }
        $qrcode=request()->file('qrcode');
        if($qrcode){
            if(is_null($qrcode_text)){
                return json('二维码名片已经存在，请勿重复发布',1);
            }
            $qrcode_text=md5($qrcode_text);
            $hasQr=model('testweixin')->where(['qrcode_text'=>$qrcode_text])->count();
            if($hasQr){
                return json('二维码名片已经存在，请勿重复发布',1);
            }
            $q=$this->loadHeadImg($qrcode);
            if(!$q['success']){
                return json($q['msg'],1);
            }
            $data['qrcode']=$q['msg'];
        }elseif($type==1&&!empty($user['qrcode'])){
            $data['qrcode']=$user['qrcode'];
        }else{
            return json('请上传二维码',1);
        }

        

        // 头像
        $head_img=request()->file('head_img');
        if($head_img){
            $h=$this->loadHeadImg($head_img);
            if(!$h['success']){
                return json($h['msg'],1);
            }
            $data['head_img']=$h['msg'];
        }else{
            $data['head_img']=$user['head_img'];
        }
        $data['uid']=$uid;
        
        if(is_null($wxId)){
            $data['wxId']=$user['wxId'];
        }
        if(is_null($city_id)){
            $data['city_id']=$user['city_id'];
        }
        if(is_null($tel)){
            $data['tel']=$user['tel'];
        }
        if(is_null($nickName)){
            $data['nickName']=$user['name'];
        }
        $time=time();
        $data['s_time']=$time;
        $data['e_time']=$time;
        if($type==2){ //群二维码有过期时间
            $data['qrcode_time']=$time+7*86400;
        }
        if(!is_null($attr)){
            $data['attr_str']=','.implode(',', $attr);
        }
        $result=true;
        $add=[];
        Db::startTrans();
        try {
            $time=time();
            $add=model('testweixin')->add($data);
            if(empty($add)){
                exception('系统繁忙，发布失败');
            }
            if($setting['money']>0){
                if($setting['coin_expire']<=$time){
                    $dec=model('member')->where([
                        'id'=>$uid,
                        'coin'=>['coin','>=',$setting['money']],
                    ])->setDec('coin',$setting['money']);
                    if(!$dec){
                        exception('扣款失败，请稍后再试');
                    }
                }
                $log=model('coinlog')->add(
                    [
                        'nums'=>0-$setting['money'],
                        'time'=>$time,
                        'uid'=>$uid,
                        'type'=>0,
                        'remark'=>'发布名片消耗',
                    ]
                );
                if(empty($log)){
                    exception('写入记录失败，请稍后再试');
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result=$e->getMessage();
        }
        if(true!==$result){
            return json($result,1);
        }
        if(is_null($attr)){
            $attr=[];
            $_a=model('member_attr')->readAll(['uid'=>$uid],0,['field'=>'attr_id']);
            foreach ($_a as $v) {
                $attr[]=$v['attr_id'];
            }
        }
        $a=[];
        foreach ($attr as $v) {
            $a[]=['wx_id'=>$add['id'],'attr_id'=>$v];
        }
        model('weixin_attr')->add($a);
        return json('发布成功');
        
    }
    /**
     * 更新名片
     * @param  integer $id   名片ID
     * @param  string|array  $attr    名片标签
     * @return [type]        [description]
     */
    function edit($id=0,$attr=null){
        $uid=$this->user['id'];
        $user=model('member')->read(['id'=>$uid],'id,head_img,wxId,city_id,is_perfect');
        if(!$user['is_perfect']){
            //return json('请先完善您的个人信息',1);
        }
        $has=model($this->table)->read(['id'=>$id],'qrcode,head_img,type');
        if(!isset($has['qrcode'])){
            return json('该记录可能已经被移除',1);
        }
        $qrcode_text=input('qrcode_text/s');
        $data=[
            'id'=>$id,
            'wxId'=>input('wxId/s'),
            'remark'=>input('remark/s'),
            'tel'=>input('tel/s'),
            'nickName'=>input('nickName/s'),
            'sex'=>input('sex/s'),
            'city_id'=>input('city_id/s'),
            'qrcode_text'=>md5($qrcode_text),
        ];
        
        $qrcode=request()->file('qrcode');
        if($qrcode){
            if(empty($qrcode_text)){
                return json('二维码名片已经存在，请勿重复发布',1);
            }
            $qrcode_text=md5($qrcode_text);
            $hasQr=model($this->table)->where(['qrcode_text'=>$qrcode_text])->count();
            if($hasQr){
                return json('二维码名片已经存在，请勿重复发布',1);
            }
            $q=$this->loadHeadImg($qrcode);
            if(!$q['success']){
                return json($q['msg'],1);
            }
            $data['qrcode']=$q['msg'];
            if($has['type']==2){
                $data['qrcode_time']=time()+7*86400;
            }

        }
        $head_img=request()->file('head_img');
        if($head_img){
            $h=$this->loadHeadImg($head_img);
            if(!$h['success']){
                return json($h['msg'],1);
            }
            $data['head_img']=$h['msg'];
        }
        foreach ($data as $k => $v) {
            if(empty($v)){
                unset($data[$k]);
            }
        }
        $data['e_time']=time();
        $edit=model($this->table)->edit($data);
        if(!$edit){
            return json('系统繁忙，更新失败',1);
        }
        // 删除过期的二维码
        if(isset($data['qrcode'])){
            $this->deleteUploadFile($has['qrcode']);
        }
        // 删除旧头像
        if(isset($data['head_img'])&&$has['head_img']!=$user['head_img']){
            $this->deleteUploadFile($has['head_img']);
        }
        if(!is_null($attr)){
            if(is_string($attr)){
                $attr=json_decode($attr,true);
            }
            model('weixin_attr')->del(['wx_id'=>$id]);
            $a=[];
            foreach ($attr as $v) {
                $a[]=['wx_id'=>$add['id'],'attr_id'=>$v];
            }
            $rs=model('weixin_attr')->add($a);
            if($rs){
                $attr_str=','.implode(',', $attr);
                model($this->table)->edit(['id'=>$add['id'],'attr_str'=>$attr_str]);
            }
        }
        return json('更新成功');
    }


    /**
     * 更新名片
     * @param  integer $id   名片ID
     * @param  integer $isUp    上下架和删除（0 下架 1 上架 2 删除)）
     * @return [type]        [description]
     */
    function editMp($id=0){
        $uid=$this->user['id'];
        $user=model('member')->read(['id'=>$uid],'id');
        $has=model($this->table)->read(['id'=>$id],'id');
        if(!isset($has['id'])){
            return json('该记录可能已经被移除',1);
        }
        $data['isUp']=input('isUp/s');
        $data['id'] = $id;
        if ($data['isUp'] == 1) {
            $data['isUp'] = 0;
        }
        elseif ($data['isUp'] == 0) {
            $data['isUp'] = 1;
        }
        elseif ($data['isUp'] == 2) {
            $datas['id'] = $id;
            $del=model($this->table)->del($datas);
            if ($del) {
                return json('删除成功');
            }
            else{
                return json('系统繁忙，删除失败',1);
            }

        }
        $edit=model($this->table)->edit($data);
        if(!$edit){
            return json('系统繁忙，更新失败',1);
        }
        return json('更新成功');
    }
}